package 数组;

/**
 * @author ssh
 * @date 2025/9/18
 * @description
 */
public class 二分查找 {
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;

        while (left <= right) {
            int mid = left + ((right - left)>>1) ; // 防止溢出

            if (nums[mid] == target) {
                return mid; // 找到目标值，返回索引
            } else if (nums[mid] < target) {
                left = mid + 1; // 目标值在右半部分
            } else {
                right = mid - 1; // 目标值在左半部分
            }
        }

        return -1; // 未找到目标值
    }

    public static void main(String[] args) {
        二分查找 solution = new 二分查找();
        int[] nums = {-1, 0, 3, 5, 9, 12};
        int target = 9;
        int result = solution.search(nums, target);
        System.out.println(result); // 输出: 4
    }
}
